package com.ddstation.onsitelaw.controller;

import com.ddstation.onsitelaw.entity.DtInvsManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.DtInvsManageInstitutionSupervisorEntity;
import com.ddstation.onsitelaw.entity.DtSupervisorEnforcementEntity;
import com.ddstation.onsitelaw.model.AccountModel;
import com.ddstation.onsitelaw.service.AccountService;
import com.ddstation.onsitelaw.service.DtHealthManageInstitutionService;
import com.ddstation.onsitelaw.service.DtInvsManageInstitutionService;
import com.ddstation.onsitelaw.service.DtSupervisorEnforcementService;
import com.ddstation.onsitelaw.utils.Constant;
import com.ddstation.onsitelaw.utils.MD5Util;
import com.ddstation.onsitelaw.utils.PageResult;
import com.ddstation.security.util.WnUserIdCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 陆青龙
 */
@Controller
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Inject
    private AccountService accountService;
    @Inject
    private DtInvsManageInstitutionService manageInstitutionService;
    @Inject
    private DtSupervisorEnforcementService supervisorEnforcementService;

    @Inject
    private DtHealthManageInstitutionService dtHealthManageInstitutionService;

    @Inject
    private DtInvsManageInstitutionService dtInvsManageInstitutionService;

    /**
     * 登录页
     */
    @RequestMapping(value = "login")
    String login(HttpServletRequest request, HttpSession session, Model model) {
        //判断用户是PC端和还是APP端登陆
        String equipmentType = accountService.judgeIsMobile(request);
        if (Constant.APP.equals(equipmentType)) {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getInstitutionId() == null) {
                //session无登录信息返回登录页
                String encryptUid = (String) session.getAttribute("encryptUid");
                int uid = WnUserIdCrypt.decryptUid(encryptUid);
                DtInvsManageInstitutionSupervisorEntity entity = dtInvsManageInstitutionService.selectByWxUserId(uid);
                if (ObjectUtils.isEmpty(entity)) {
                    model.addAttribute("encryptUid", encryptUid);
                    return "app/notAuthority";
                }
                userLogin(entity.getLoginUser(), entity.getLoginPassword(), session, "1");
            }
            return "app/mainApp";
        }
        return "login";
    }


    /**
     * 登录超时
     */
    @RequestMapping(value = "loginTimeout")
    String loginTimeout(Model model) {
        model.addAttribute("code", 0);
        model.addAttribute("msg", "登录状态已失效，请重新登录!");
        return "login";
    }


    /**
     * 退出登录
     */
    @RequestMapping(value = "logout")
    String logout(HttpSession session) {
        //清除登录session信息
        session.removeAttribute("account");
        return "login";
    }

    @RequestMapping(value = "main")
    String main(HttpSession session, Model model) {
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getInstitutionId() == null) {
            //session无登录信息返回登录页
            model.addAttribute("code", 0);
            model.addAttribute("msg", "登录状态已失效，请重新登录!");
            return "login";
        }
        //获取其中机构ID等信息
        model.addAttribute("account", account);
        return "main";
    }

    @RequestMapping("login.do/userLogin")
    @ResponseBody
    Map<String, Object> userLogin(
            @RequestParam String userLogin,//登录账号
            @RequestParam String userPassword,//登录密码
            HttpSession session, String isEncode) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("errCode", -1);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            AccountModel account;
            if (StringUtils.isEmpty(isEncode)) {
                account = accountService.login(userLogin, MD5Util.md5Encode(userPassword));
            } else {
                account = accountService.login(userLogin, userPassword);
            }

            if (ObjectUtils.isEmpty(account)) {
                //账号密码不存在
                map.put("errMsg", "用户名或密码错误");
                return map;
            }


            DtInvsManageInstitutionEntity manageInstitutionEntity = manageInstitutionService.selectById(account.getInstitutionId());
            if (ObjectUtils.isEmpty(manageInstitutionEntity)) {
                //管理区域信息不存在
                map.put("errMsg", "账户信息异常，请联系管理员");
                return map;
            }
            //市级管理员是的区code是空的
            if ("".equals(manageInstitutionEntity.getCounty())) {
                manageInstitutionEntity.setCounty(null);
            }
            account.setManageInstitutionEntity(manageInstitutionEntity);

            //管理员账号
            if (account.getRoleId() == 1) {
                HashMap paramMap = new HashMap();
                paramMap.put("invsId", manageInstitutionEntity.getId());
                paramMap.put("institutionalName", null);
                paramMap.put("county", manageInstitutionEntity.getCounty());
                paramMap.put("pageNum", 1);
                paramMap.put("pageSize", 100000);
                PageResult pageResult = dtHealthManageInstitutionService.selectAllHealthManageList(paramMap);
                account.setDtHealthManageInstitutionEntityList(pageResult.getRows());
            }
            //督察员账号
            if (account.getRoleId() == 2) {
                //督察员获取管理机构集合
                List<DtSupervisorEnforcementEntity> enforcementList = supervisorEnforcementService.selectListBySupervisorId(account.getSupervisorId());
                if (ObjectUtils.isEmpty(enforcementList)) {
                    //管理机构集合不存在
                    map.put("errMsg", "账户信息异常，请联系管理员");
                    return map;
                }
                account.setEnforcementList(enforcementList);
            }
            //保存用户信息到session
            session.setAttribute("account", account);
            //请求成功
            map.put("errCode", 0);
            map.put("errMsg", "请求成功");
            map.put("account", account);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户登录异常" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("updatePassword.do")
    @ResponseBody
    Map<String, Object> updatePassword(
            @RequestParam String password,//原密码
            @RequestParam String newPassword,//新密码
            HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                //session无登录信息返回登录页
                map.put("errCode", -1);
                map.put("errMsg", "登录状态已失效,请重新登录!");
                return map;
            }
            //校验原密码与session信息中信息是否匹配
            if (!MD5Util.md5Encode(password).equals(account.getLoginPassword())) {
                map.put("errMsg", "原密码输入错误,请重新输入!");
                return map;
            }
            //校验新密码格式
            if (newPassword.length() < 6 || newPassword.length() > 16) {
                map.put("errMsg", "密码长度应为6-16位!");
                return map;
            }
            //修改密码
            accountService.updatePassword(account.getSupervisorId(), MD5Util.md5Encode(newPassword));
            //替换session中原密码
            account.setLoginPassword(MD5Util.md5Encode(newPassword));
            session.setAttribute("account", account);
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户登录异常" + e.getMessage());
        }
        return map;
    }

    /**
     * 跳转医疗机查询界面
     */
    @RequestMapping(value = "queryInstitution")
    String queryInstitution() {
        return "app/queryInstitution";
    }


}